package org.noip2.noskamaru.katsys;

import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Timestamp;

public class MainServer implements Runnable{
	public static  int port=4444;
	Socket socket;
	PrintWriter out=null;
	BufferedReader in=null;	
	public MainServer(Socket socket)	{		//constructor
		this.socket=socket;
		
	}
	
	public static void main(String args[]) throws IOException 	{
		new Usernametest();
		System.out.println("server is running .........");
		ServerSocket ss=new ServerSocket(port);
		try	{
			
			while(true)	{
				Socket s=null;			
				s=ss.accept();
				new Thread(new MainServer(s)).start();
				
			}
		}
		
		finally		{
			if(ss!=null)	{
				ss.close();
			}
		}
	}
	
	public void run()	{
		try	{	
			out=new PrintWriter(socket.getOutputStream(),true);
			in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
			String inusername=in.readLine();
			String inpassword=in.readLine();
				if(Usernametest.loginClient(inusername,inpassword)==true)	{
				java.util.Date date= new java.util.Date();
				try 	{
					     FileWriter outFile = new FileWriter("logs.txt");
					     PrintWriter printFile = new PrintWriter(outFile);				      
					     
					     printFile.print(inusername + " accessed the system at:");
					     printFile.print(new Timestamp(date.getTime()));
					     printFile.println();
					     printFile.close();
				} 
				
				catch (IOException e)	{
					e.printStackTrace();
				}
				
			out.println("4445");//service location
			}
			else	{
				out.println("0");
			}
		} 
		catch (IOException e) {

			e.printStackTrace();
		}
		finally		{
				if(in !=null)	{
					try {
						in.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				if(out != null)		{
					out.close();
				}
				
			}
	
	
	
	}
}
